<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-goods"></i> 商城商品
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-input v-model="search" placeholder="商品名称" class="handle-input mr10" width="55"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="getData()">搜索</el-button>
        <el-button type="primary" icon="el-icon-lx-add" @click="showBox()">添加商品</el-button>
      </div>
      <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header" :row-style="{ height: '80px' }">
        <el-table-column prop="name" label="商品名称"></el-table-column>
        <el-table-column prop="showPic" label="展示图片">
          <template #default="scope">
            <el-image class="table-td-thumb" :src="joinpic(scope.row.showPic)" fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="money" label="秒杀价"></el-table-column>
        <el-table-column prop="marketMoney" label="原价"></el-table-column>
        <el-table-column prop="status" label="商品状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status == '0'" type="success">上架</el-tag>
            <el-tag v-else type="danger">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button type="text" icon="el-icon-lx-attention" @click="handleCheak(scope.row)">查看</el-button>
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" @click="handleState(scope.row)">{{ scope.row.status == 0 ? "下架" : "上架" }}</el-button>
            <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex" :page-size="query.pageSize" :total="query.pageTotal" @current-change="handlePageChange"></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="创建" v-model="showAddUser" width="70%">
      <el-form ref="form" :model="list" label-width="100px" :disabled="isDisabled">
        <el-row>
          <el-col :span="8">
            <el-form-item label="商品名称"> <el-input v-model="from.name" /> </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="原价"> <el-input v-model="from.marketMoney" type="number" /> </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="秒杀价"> <el-input v-model="from.money" type="number" /> </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规格"> <el-input v-model="from.standard" placeholder="以 / 分割规格" /> </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="尺码"> <el-input v-model="from.sizes" placeholder="以 / 分割尺码"></el-input> </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="型号"> <el-input v-model="from.model" placeholder="以 / 分割型号"></el-input> </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库存"> <el-input v-model="from.stock" type="number" /> </el-form-item>
          </el-col>
          <el-col :span="8" v-if="isChange != 1">
            <el-form-item label="销量"> <el-input v-model="from.sales" /> </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开始时间">
              <el-date-picker v-model="from.startTime" type="datetime" placeholder="选择开始时间"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间">
              <el-date-picker v-model="from.endTime" type="datetime" placeholder="选择结束时间"></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="商品图片">
              <div class="crop-demo">
                <img v-if="from.showPic" :src="joinpic(from.showPic)" class="pre-img" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <input class="crop-input" type="file" name="image" accept="image/*" @change="setImage" :disabled="isDisabled" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="展示图片">
              <el-upload action="" list-type="picture-card" :http-request="uploadFileMethod" :on-preview="picPreview" multiple :file-list="picList" :on-remove="picRemove" :class="{ hide: hideUploadCard }" ref="picClear">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog v-model="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="详情">
          <Tinymce-editor :disabled="isDisabled" :value="from.contextDetails" @input="(res) => (from.contextDetails = res)"></Tinymce-editor>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddUser = false">取 消</el-button>
          <el-button v-if="isChange == 1" type="primary" @click="append">确 定</el-button>
          <el-button v-else type="primary" @click="edit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { upload, api } from "@/api/index";
import { formatDate } from "@/common/data";
import TinymceEditor from "@/components/tinymce-editor";
import moment from "moment";
export default {
  inject: ["reload"],
  filters: {
    formatDate(time) {
      time = time * 1000;
      let date = new Date(time);
      console.log(new Date(time));
      return formatDate(date, "yyyy-MM-dd hh:mm");
    },
  },
  components: { TinymceEditor },
  name: "basetable",
  data() {
    return {
      username: localStorage.getItem('ms_username'),
      query: {
        pageNo: 1,
        pageTotal: 0,
      },
      search: "",
      tableData: [],
      showAddUser: false,
      from: {},
      isChange: "",
      fileList: [],
      picList: [],
      isDisabled: false,
      dialogVisible: false,
      hideUploadCard: false,
    };
  },
  created() {
    this.getData();
  },
  methods: {
    dateFormat: function (row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    // 获取分类列表
    getData() {
      api('/web/seckillCommodity/g', {
        limit: 10,
        offset: this.query.pageNo,
      }).then((res) => {
        this.tableData = res.data.rows;
        this.query.pageTotal = res.data.total;
      });
    },
    // 分页导航
    handlePageChange(val) {
      this.query.pageNo = val;
      this.getData();
    },

    //创建分类
    append() {
      this.from.showDetails1 = this.fileList[0];
      this.from.showDetails2 = this.fileList[1];
      this.from.showDetails3 = this.fileList[2];
      this.from.endTime1 = this.$filters.formatTime(this.from.endTime)
      this.from.startTime1 = this.$filters.formatTime(this.from.startTime)
      api('/web/seckillCommodity/a', this.from).then((res) => {
        if (res.code === 2000) {
          this.$message.success(res.message);
          this.from = {};
          this.reload();
          this.showAddUser = false;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    joinpic(item) {
      return `http://xiuhaoshenghuo.xsiuyang.com/imgs/${item}`
    },
    //预览大图
    picPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //移除图片
    picRemove(file, fileList) {
      this.fileList = [];
      for (const i in fileList) {
        this.fileList.push(fileList[i].url);
        if (fileList[i].raw) {
          this.uploadFileMethod(fileList[i].raw);
        }
      }
    },
    //多图上传
    uploadFileMethod(param) {
      let formData = new FormData();
      if (param.file) {
        formData.append("file", param.file);
      } else {
        formData.append("file", param);
      }
      upload(formData).then((res) => {
        this.fileList.push(this.joinpic(res.data[0].fileName));
        console.log(this.fileList);
        this.hideUploadCard = this.fileList.length >= this.isType;
      });
    },
    //上传图片
    setImage(file) {
      let imgFile = file.target.files[0];
      let formData = new FormData(); //通过formdata上传
      formData.append("file", imgFile);
      upload(formData).then((res) => {
        this.from.showPic = res.data[0].fileName;
      });
    },
    //显示编辑框
    showBox() {
      this.showAddUser = true;
      this.isChange = 1;
      this.isDisabled = false;
    },
    // 删除操作
    handleDelete(row) {
      // 二次确认删除
      let data = JSON.parse(JSON.stringify(row));
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      }).then(() => {
        api('/web/seckillCommodity/d', { id: data.id }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message);
            this.reload();
          } else {
            this.$message.error(res.message);
          }
        });
      })
    },
    //查看操作
    handleCheak(row) {
      this.picList = [];
      this.isDisabled = true;
      this.showAddUser = true;
      this.isChange = 0;
      let data = JSON.parse(JSON.stringify(row));
      this.picList.push(data.showDetails1);
      this.picList.push(data.showDetails1);
      this.picList.push(data.showDetails1);
      this.from = data;
    },
    // 编辑操作
    handleEdit(row) {
      this.picList = [];
      let data = JSON.parse(JSON.stringify(row));
      this.from = data;
      this.isDisabled = false;
      this.showAddUser = true;
      this.isChange = 0;
      this.picList.push({ name: "1", url: data.showDetails1 });
      this.picList.push({ name: "2", url: data.showDetails2 });
      this.picList.push({ name: "3", url: data.showDetails3 });
      // console.log(this.picList);
    },
    //修改分类
    edit() {
      if (this.fileList.length == 0) {
        for (const i in this.picList) {
          this.fileList.push(this.picList[i].url);
        }
      }
      this.from.showDetails1 = this.fileList[0];
      this.from.showDetails2 = this.fileList[1];
      this.from.showDetails3 = this.fileList[2];
      this.from.endTime1 = this.$filters.formatTime(this.from.endTime)
      this.from.startTime1 = this.$filters.formatTime(this.from.startTime)
      api('/web/seckillCommodity/u', this.from).then((res) => {
        if (res.code == 2000) {
          this.showAddUser = false;
          this.$message.success("修改商品成功");
          this.from = {};
          this.reload();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //上下架
    handleState(row) {
      let data = JSON.parse(JSON.stringify(row));
      this.$confirm("确定改变状态", "提示", {
        type: "warning",
      }).then(() => {
        api('/web/seckillCommodity/up', { id: data.id, status: data.status == 0 ? "1" : "0", }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message);
            this.reload();
          } else {
            this.$message.error(res.message);
          }
        });
      })
    },
  },
};
</script>
<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>
<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.green {
  color: #0ab618;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  height: 60px;
}

.crop-demo {
  display: flex;
  align-items: flex-end;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 148px;
  height: 148px;

  .pre-img {
    width: 146px;
    height: 146px;
    background: #f8f8f8;
    border: 1px solid #eee;
    border-radius: 5px;
    object-fit: cover;
  }

  .crop-input {
    position: absolute;
    width: 148px;
    height: 148px;
    left: 0px;
    top: 0px;
    opacity: 0;
    cursor: pointer;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
}
</style>
